import React, { useCallback, useState, useEffect } from 'react';
import { Upload, Button, Typography, Card, message, Space } from 'antd';
import { UploadOutlined, InboxOutlined, DeleteOutlined } from '@ant-design/icons';
import './ImageUploader.css';

const { Dragger } = Upload;
const { Title, Text } = Typography;

const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];

const ImageUploader = ({ onImageUpload, disabled }) => {
  const [previewImage, setPreviewImage] = useState(null);
  const [imageInfo, setImageInfo] = useState(null);

  // 在disabled状态变化时清除错误信息
  useEffect(() => {
    if (disabled) {
      message.destroy(); // 清除所有消息
    }
  }, [disabled]);

  const resetImage = useCallback(() => {
    setPreviewImage(null);
    setImageInfo(null);
    onImageUpload(null);
  }, [onImageUpload]);

  const handleImageLoad = useCallback((file) => {
    // 验证图片类型
    if (!ALLOWED_TYPES.includes(file.type)) {
      message.error('只支持JPEG、PNG和WebP格式的图片！');
      return false;
    }
    
    // 验证图片大小
    if (file.size > MAX_FILE_SIZE) {
      message.error('图片大小不能超过10MB！');
      return false;
    }

    // 读取图片并设置预览
    const reader = new FileReader();
    reader.onload = (e) => {
      const imageUrl = e.target.result;
      setPreviewImage(imageUrl);
      
      // 获取图片尺寸信息
      const img = new Image();
      img.onload = () => {
        setImageInfo({
          width: img.width,
          height: img.height,
          size: (file.size / 1024 / 1024).toFixed(2)
        });
      };
      img.src = imageUrl;
      
      onImageUpload(imageUrl);
    };
    reader.readAsDataURL(file);
    
    return false; // 阻止自动上传
  }, [onImageUpload]);

  const beforeUpload = useCallback((file) => {
    if (disabled) return false;
    return handleImageLoad(file);
  }, [disabled, handleImageLoad]);

  const loadExampleImage = useCallback((url, dimensions = "512x512") => {
    if (disabled) return;
    
    fetch(url)
      .then(response => {
        if (!response.ok) throw new Error('加载示例图片失败');
        return response.blob();
      })
      .then(blob => {
        const file = new File([blob], 'example.jpg', { type: 'image/jpeg' });
        handleImageLoad(file);
      })
      .catch(error => {
        message.error('加载示例图片失败: ' + error.message);
      });
  }, [disabled, handleImageLoad]);

  return (
    <div className="image-uploader">
      <Card className="uploader-card">
        <div className="uploader-header">
          <Title level={4}>上传图片</Title>
          {previewImage && (
            <Button 
              icon={<DeleteOutlined />} 
              onClick={resetImage}
              disabled={disabled}
              size="small"
            >
              移除
            </Button>
          )}
        </div>
        
        <Text type="secondary">支持JPEG、PNG、WebP等格式，大小不超过10MB</Text>
        
        <Dragger
          name="file"
          multiple={false}
          showUploadList={false}
          beforeUpload={beforeUpload}
          customRequest={({ onSuccess }) => setTimeout(() => onSuccess("ok"), 0)}
          className={`upload-area ${disabled ? 'disabled' : ''}`}
          disabled={disabled}
        >
          {previewImage ? (
            <div className="preview-container">
              <img src={previewImage} alt="预览图" className="preview-image" />
              <div className="preview-overlay">
                {imageInfo && (
                  <div className="image-info">
                    <Text>{`${imageInfo.width}×${imageInfo.height}像素 (${imageInfo.size}MB)`}</Text>
                  </div>
                )}
                {!disabled && <Text>点击或拖拽更换图片</Text>}
              </div>
            </div>
          ) : (
            <div className="upload-hint">
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖放图片到此区域上传</p>
              <p className="ant-upload-hint">
                建议分辨率：1024×1024像素
              </p>
            </div>
          )}
        </Dragger>

        {/* 示例图片区域 */}
        <div className="example-images">
          <Text type="secondary">或者使用示例图片：</Text>
          <div className="example-thumbnails">
            <div 
              className={`example-thumbnail ${disabled ? 'disabled' : ''}`} 
              onClick={() => !disabled && loadExampleImage('https://picsum.photos/512/512?random=1')}
            >
              <img src="https://picsum.photos/100/100?random=1" alt="示例1" />
            </div>
            <div 
              className={`example-thumbnail ${disabled ? 'disabled' : ''}`} 
              onClick={() => !disabled && loadExampleImage('https://picsum.photos/512/512?random=2')}
            >
              <img src="https://picsum.photos/100/100?random=2" alt="示例2" />
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default ImageUploader;